<?php

namespace app\group\controller\admin\goods;

use sheep\controller\Backend;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;
use app\group\service\goods\GoodsService;
use app\group\model\goods\Goods as GoodsModel;
use app\group\validate\admin\goods\Goods as GoodsValidate;

class Goods extends Backend
{
    public $organ_id;

    public function initialize()
    {
        $this->organ_id = $this->shopId();
        $this->model = new GoodsModel;
    }

    /**
     * 商品列表
     *
     * @return \think\Response
     */
    public function list(Request $request)
    {
        $user = $this->auth()->user();
        $store_id = $this->shopId();
        $param = $request->param();
        $where = [];
        if ($user->role_id != 1) {
            $param['store_id'] = $store_id;
            $where[] = ['organ_id', '=', $user->organ_id];
        }
        $goods = $this->model->getList($param);

        $category_id = Db::name('organ_category')->where('audit_status', 'normal')->where($where)->column('category_id');
        $category_list = Db::name('shop_category')->where('id', 'in', $category_id)->column('name', 'id');

        foreach ($goods as $k => $v) {
            $goods[$k]['category_id_text'] = $category_list[$v['category_id']] ?? '' ;
        }
        return success('获取成功', $goods);
    }

    /**
     * 服务分类
     *
     * @return \think\Response
     */
    public function category_list(Request $request)
    {
//        $category_list = $this->model->categoryList();
        $user = $this->auth()->user();
        $where = [];
        if ($user->role_id != 1) {
            $where[] = ['organ_id', '=', $user->organ_id];
        }

        $category_id = Db::name('organ_category')->where('audit_status', 'normal')->where($where)->column('category_id');
        $category_list = Db::name('shop_category')->field('id, name as title')->where('id', 'in', $category_id)->select()->toArray();

        return success('获取成功', [[
            'id' => '-1',
            'title' => '选择',
            'children' => $category_list
        ]]);
    }

    /**
     * 毛长
     *
     * @return \think\Response
     */
    public function hair_list(Request $request)
    {
        $hair_list = $this->model->hairList();
        return success('获取成功', $hair_list);
    }

    // 添加
    public function add(Request $request)
    {
        $param = $request->only([
            'category_id', 'title', 'image', 'stocks', 'original_price', 'is_discount', 'discount', 'is_limit', 'hair', 'weight', 'validity', 'subscribe', 'status', 'apply', 'explain', 'details', 'limit_num', 'product_list'
        ]);
        try {
            validate(GoodsValidate::class)
                ->scene('add')
                ->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return error($e->getError());
        }
        $user              = $this->auth()->user();
        $param['organ_id'] = $user->organ_id;
        $param['store_id'] = $this->organ_id;

        $param['create_people_id'] = $user->id;
        $param['create_people']    = $user->account;

        $param['price'] = $param['original_price'];
        // 计算折扣之后的价格
        if ($param['is_discount'] == 1) {
            $param['price'] = $param['discount'] * $param['original_price'] * 0.1;
        }

        $result = $this->model->dataCreate($param);
        if (!$result) {
            return error('保存失败');
        }

        // 同步萌宠霸王
        unset($param['create_people_id']);
        unset($param['create_people']);
        $param['sub_title']           = $param['title'];
        $param['saas_group_goods_id'] = $result->id;
        $param['create_time']         = time();
        $param['update_time']         = time();
        $param['product_list']        = json_encode($param['product_list'], JSON_UNESCAPED_UNICODE);
        $cutepetDb                    = Db::connect('mysql_cutepet');
        $cutepetGroupGoods            = $cutepetDb->name('group_goods')->insert($param);
        if (!$cutepetGroupGoods) {
            return error('同步萌宠霸王失败');
        }

        return success('保存成功');
    }

    /**
     * 商品详情
     *
     * @return \think\Response
     */
    public function detail(Request $request, $id)
    {
        $goods = $this->model->detail($id);
        return success('获取成功', $goods);
    }

    // 编辑
    public function edit(Request $request, $id)
    {
        $param = $request->only([
            'category_id', 'title', 'image', 'stocks', 'original_price', 'is_discount', 'discount', 'is_limit', 'hair', 'weight', 'validity', 'subscribe', 'status', 'apply', 'explain', 'details', 'limit_num', 'product_list'
        ]);
        try {
            validate(GoodsValidate::class)
                ->scene('edit')
                ->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return error($e->getError());
        }
        $user = $this->auth()->user();
        $param['id'] = $id;
        $param['update_people_id'] = $user->id;
        $param['update_people'] = $user->account;
        $param['price'] = $param['original_price'];
        // 计算折扣之后的价格
        if ($param['is_discount'] == 1)
        {
            $param['price'] = $param['discount'] * $param['original_price'] * 0.1;
        }

        $result = $this->model->dataEdit($param);
        if (!$result) {
            return error('编辑失败');
        }
        // 同步萌宠霸王
        unset($param['id']);
        unset($param['update_people_id']);
        unset($param['update_people']);
        $param['sub_title']    = $param['title'];
        $param['update_time']  = time();
        $param['product_list'] = json_encode($param['product_list'], JSON_UNESCAPED_UNICODE);

        $cutepetDb             = Db::connect('mysql_cutepet');
        $cutepetGroupGoods     = $cutepetDb->name('group_goods')->where('saas_group_goods_id', $id)->update($param);
        if (!$cutepetGroupGoods) {
            return error('同步萌宠霸王失败');
        }

        return success('编辑成功');
    }

    // 编辑状态
    public function statusEdit(Request $request)
    {
        $param = $request->only([
            'id', 'status'
        ]);
        if (empty($param['id']) || empty($param['status'])) {
            return error('参数有误');
        }
        $user = $this->auth()->user();
        $param['update_people_id'] = $user->id;
        $param['update_people'] = $user->account;

        $result = $this->model->dataStatusEdit($param);
        if (!$result) {
            return error('修改失败');
        }

        // 同步萌宠霸王
        $id = $param['id'];
        unset($param['id']);
        unset($param['update_people_id']);
        unset($param['update_people']);
        $param['update_time']  = time();

        $cutepetDb             = Db::connect('mysql_cutepet');
        $cutepetGroupGoods     = $cutepetDb->name('group_goods')->where('saas_group_goods_id', $id)->update($param);
        if (!$cutepetGroupGoods) {
            return error('同步萌宠霸王失败');
        }

        return success('修改成功');
    }

    // 入库
    public function inStock(Request $request)
    {
        $param = $request->only([
            'id', 'stocks'
        ]);

        if (empty($param['id']) || empty($param['stocks'])) {
            return error('参数有误');
        }
        $result = $this->model->inStock($param);
        if (!$result) {
            return error('入库失败');
        }

        // 同步萌宠霸王
        $id = $param['id'];
        unset($param['id']);
        $param['update_time']  = time();

        $cutepetDb             = Db::connect('mysql_cutepet');
        $cutepetGroupGoods     = $cutepetDb->name('group_goods')->where('saas_group_goods_id', $id)->inc('stocks', $param['stocks'])->update();
        if (!$cutepetGroupGoods) {
            return error('同步萌宠霸王失败');
        }

        return success('入库成功');
    }

    // 出库
    public function outStock(Request $request)
    {
        $param = $request->only([
            'id', 'stocks'
        ]);

        if (empty($param['id']) || !isset($param['stocks'])) {
            return error('参数有误');
        }
        if ($param['stocks'] <= 0) {
            return error('出库数不能为0');
        }

        $detail_data = $this->model->detail($param['id']);
        if ($param['stocks'] > $detail_data['stocks'])
        {
            return error('出库数不能大于库存数');
        }

        $result = $this->model->outStock($param);
        if (!$result) {
            return error('出库失败');
        }

        // 同步萌宠霸王
        $id = $param['id'];
        unset($param['id']);
        $param['update_time']  = time();

        $cutepetDb             = Db::connect('mysql_cutepet');
        $cutepetGroupGoods     = $cutepetDb->name('group_goods')->where('saas_group_goods_id', $id)->dec('stocks', $param['stocks'])->update();
        if (!$cutepetGroupGoods) {
            return error('同步萌宠霸王失败');
        }

        return success('出库成功');
    }

    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function delete($id)
    {
        if (empty($id))
        {
            return error('参数有误');
        }
        $result = $this->model->deleteData($id);
        if (!$result) {
            return error('删除失败');
        }
        // 同步萌宠霸王
        $param['update_time']  = time();
        $param['delete_time']  = time();

        $cutepetDb             = Db::connect('mysql_cutepet');
        $cutepetGroupGoods     = $cutepetDb->name('group_goods')->where('saas_group_goods_id', $id)->update($param);
        if (!$cutepetGroupGoods) {
            return error('同步萌宠霸王失败');
        }

        return success('删除成功');
    }
}